using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Pegasus.Diagnostics;

namespace Pegasus.Xml.Serialization
{

	/// <summary>
	/// Class provides helper methods to serialize/deserialize object using the XmlSerializer.
	/// </summary>
	public static class XmlSerializationHelper
	{
		/// <summary>
		/// Serialize an Objects to XML using the XmlSerializer process.
		/// </summary>
		/// <param name="objectToSerialize">The object to serialize.</param>
		/// <returns></returns>
		public static string ObjectToXml( object objectToSerialize )
		{
			// Check Parameters
			ParamCode.AssertNotNull( objectToSerialize, "objectToSerialize" );

			using( MemoryStream memStream = new MemoryStream() )
			{
				XmlSerializer xmlSerializer = new XmlSerializer( objectToSerialize.GetType() );
				xmlSerializer.Serialize( memStream, objectToSerialize );
				memStream.Flush();

				return UTF8Encoding.UTF8.GetString( memStream.GetBuffer(), 0, (int) memStream.Position );
			}
		}

		/// <summary>
		/// XMLs the serialization to object.
		/// </summary>
		/// <param name="xml">The XML.</param>
		/// <returns></returns>
		public static T XmlToObject<T>( string xml )
		{
			// Check Parameters
			ParamCode.AssertNotEmpty( xml, "xml" );

			using( MemoryStream memStream = new MemoryStream( UTF8Encoding.UTF8.GetBytes( xml ) ) )
			{
				XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );
				return (T) xmlSerializer.Deserialize( memStream );
			}
		}
	}
}
